package com.singfan.core.util;

import com.singfan.core.LoggerFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * Author: hansonghe
 * Date: 2015-08-21 12:02
 * Desc:
 */
public class SmsUtil {
    private static Logger traceLog = LoggerFactory.getTraceLogger();

    private static final String SMS_URL = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
    private static final String ACCOUNT = "cf_xingfaner";
    private static final String PASSWORD = "1234567";

    private static final String SERCURITY_CODE_TEMP = "您的验证码为【%1$s】，欢迎您成为星范儿用户！";
    private static final String CUSTOMER_ORDER_CODE = "下单成功，您的消费验证码是【%1$s】，请您凭该验证码到店进行消费，感谢您使用星范儿平台！";


    public static boolean sendSecurityCode(String phoneNumber, String sercurityCode){
        return sendSms(phoneNumber, SERCURITY_CODE_TEMP, sercurityCode);
    }

    public static boolean sendReservationCode(String phoneNumber, String reservationCode){
        return sendSms(phoneNumber, CUSTOMER_ORDER_CODE, reservationCode);
    }

    private static boolean sendSms(String phoneNumber, String smsTemp, String param){
        boolean result = false;

        try {
            HttpClient client = new HttpClient();
            PostMethod method = new PostMethod(SMS_URL);

            client.getParams().setContentCharset("UTF-8");
            method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

            String content = String.format(smsTemp, param);

            NameValuePair[] data = {//提交短信
                    new NameValuePair("account", ACCOUNT),
                    new NameValuePair("password", PASSWORD),
                    new NameValuePair("mobile", phoneNumber),
                    new NameValuePair("content", content),
            };

            method.setRequestBody(data);

            client.executeMethod(method);

            String SubmitResult =method.getResponseBodyAsString();

            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();

            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");


            if("2".equals(code)){
                result = true;
            }

            traceLog.debug(String.format("SmsUtil.sendSms() -> phoneNumber:%1$s, content:%2$s, code:%3$s, msg:%4$s, smsId:%5$s", phoneNumber, content, code, msg, smsid));
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    //
}
